<template>
  <el-dialog v-model="isShowPrint"
             :before-close="handleClose"
             title="入库单打印"
             draggable
             width="80%"
  >
    <div style="height: 700px;overflow: auto;">
      <div>
        <el-button type="danger" @click="batchDelete">删除所选</el-button>
      </div>
      <vxe-table
          ref="tablePrintRef"
          border
          :row-config="{isCurrent: true, isHover: true}"
          style="margin-top: 10px;"
          align="center"
          :data="printData"
          height="400"
          :checkbox-config="{ trigger:'row'}">
        <vxe-column type="checkbox" width="60"></vxe-column>
        <vxe-column type="seq" width="80" title="序号"></vxe-column>
        <vxe-column field="receiptCode" width="200" title="入库单号"></vxe-column>
        <vxe-column field="warehouseName" width="300" title="入库仓库"></vxe-column>
        <vxe-column field="totalNum" width="100" title="待收货数量">
        </vxe-column>
        <vxe-column field="skuName" min-width="220" title="商品信息">
          <template #default="{row}">
            <div v-for="(item,index) in row.details" :key="index">
              {{item.skuName}} &emsp; {{item.totalNum}}件
            </div>
          </template>
        </vxe-column>
        <vxe-column width="120" title="打印类型">
          <template #default>
            A4打印
          </template>
        </vxe-column>
        <vxe-column width="150" title="打印数量">
          <template #default="{row}">
            <el-input v-model="row.printNum" @input="row.printNum=limitIntNumber(row.printNum)" @change="changePrintNum"
                      clearable/>
          </template>
        </vxe-column>
        <vxe-column fixed="right" width="150" title="操作">
          <template #default="{row}">
            <el-button type="text" style="color:green" @click="clickView(row)">预览</el-button>
            <el-button type="text" style="color:red" @click="handleDelete(row)">删除</el-button>
          </template>
        </vxe-column>

      </vxe-table>
      <div style="margin: 10px 0;">
        <span>打印数量合计: <span style="font-size: 18px;color: red;">{{ printNumTotal }}</span></span>

        <span style="margin-left: 10px;">
        打印机:
        <el-select v-model="printMachine" clearable placeholder="打印机" style="width: 300px;">
          <template v-for="(item,index) in printNameList" :key="index">
            <el-option
                :label="item"
                :value="item"
            />
          </template>
        </el-select>
      </span>
        <el-button style="margin-left: 10px;" type="primary" @click="clickPrint">打印</el-button>
        <el-button style="margin-left: 10px;" type="primary" @click="clickPrintAndClose">打印并返回</el-button>
      </div>

      <!--    打印区域-->
      <div>
        <template v-for="(item,index) in printObj" :key="index">
          <div :ref="'printDiv'+item.receiptId" style="padding: 20px;width: 210mm;height: 297mm;">
            <div style="font-size: 24px;font-weight: bold;text-align: center;">入库单</div>
            <div style="width: 100%;height: 130px;">
              <div style="float: right;">
                <svg :id="'barcode'+item.receiptId"></svg>
              </div>
            </div>
            <el-row>
              <el-col :span="8">订单类型: {{ returnDictLabel(receipt_type, item.receiptType) }}</el-col>
              <el-col :span="8">供应商:{{ item.vendorName }}</el-col>
              <el-col :span="8">仓库:{{ item.warehouseName }}</el-col>
            </el-row>
            <el-row>
              <el-col :span="8">创建人:{{item.createByName}}</el-col>
              <el-col :span="8">创建时间:{{item.createTime}}</el-col>
              <el-col :span="8">备注:{{item.remark}}</el-col>
            </el-row>
            <vxe-table
                border
                :row-config="{isCurrent: true, isHover: true}"
                align="center"
                style="margin-top: 10px;"
                :data="item.details" >
              <vxe-column type="seq" width="80" title="序号"></vxe-column>
              <vxe-column field="skuCode" width="180" title="SKU编码"></vxe-column>
              <vxe-column field="skuName" width="180" title="商品名称"></vxe-column>
              <vxe-column field="totalNum" width="100" title="采购数量">
              </vxe-column>
              <vxe-column field="receiptNum" width="100" title="收货数量"></vxe-column>
              <vxe-column field="qcPassNum" width="100" title="合格数量">
              </vxe-column>

            </vxe-table>
          </div>
        </template>
      </div>
    </div>


  </el-dialog>
</template>

<script setup>
import {getCurrentInstance, nextTick, onMounted} from "vue";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {getLodop} from "@/assets/LodopFuncs";
import {getPrintConfigList} from "@/api/scApi";
import JsBarcode from "jsbarcode";
import {limitIntNumber} from "@/utils/shuangcheng";
import html2canvas from "html2canvas";

const {proxy} = getCurrentInstance();
const {receipt_type} = proxy.useDict("receipt_type");
const props = defineProps({
  isShowPrint: {
    type: Boolean,
    default: false
  },
  printData: {type: Object},
})

let printMachine = ref("") //打印机名称
let printNameList = ref([])
let printNumTotal = ref(0) //打印数量合计

let LODOP;
onMounted(() => {
  getGoodsTempList()
  setTimeout(() => {
    LODOP = getLodop();
    getPrinterCount()
  }, 500)
  props.printData.map(item=>{
    item.printNum =1
    return item
  })

})

const emits = defineEmits(['cancel'])

function handleClose() {
  emits('cancel')
}

//删除
function handleDelete(row) {
  tableData.value = tableData.value.filter(item => item.receiptId !== row.receiptId)
}

//删除所选
function batchDelete() {
  const $table = proxy.$refs.tablePrintRef
  if ($table) {
    const selectRecords = $table.getCheckboxRecords()
    if (selectRecords.length === 0) {
      proxy.$modal.msgWarning("请选择要删除的数据!")
    } else {
      tableData.value = tableData.value.filter(item => !selectRecords.some(selObj => selObj.receiptId === item.receiptId))
    }
  }
}

//获取打印机
function getPrinterCount() {
  LODOP = getLodop();
  if (LODOP) {
    //获取打印机个数
    let printNum = LODOP.GET_PRINTER_COUNT();
    for (let i = 0; i < printNum; i++) {
      printNameList.value.push(LODOP.GET_PRINTER_NAME(i))
    }
  }
}

//预览
function clickView(row) {
  printFunc(row)
}

let printObj=ref([]) //要打印的数据

function clickPrint() {

  const $table = proxy.$refs.tablePrintRef
  if ($table) {
    const selectRecords = $table.getCheckboxRecords()
    if (selectRecords.length === 0) {
      proxy.$modal.msgWarning("请选择要打印的数据!")
    } else {
      printObj.value=selectRecords
      console.log( printObj.value)
      nextTick(() => {
        for (let i = 0; i <printObj.value.length; i++) {
          let obj = printObj.value[i]
          JsBarcode("#barcode" + obj.receiptId, obj.receiptCode, {
            fontSize: 24,
            height: 40,
            fontOptions: 'bold',
            displayValue: true //是否在条形码下方显示文字
          });
          if (obj.printNum && obj.printNum * 1 > 1) {
            //同一个商品条码打印多次
            for (let j = 0; j < obj.printNum * 1; j++) {
              setTimeout(()=>{
                printFunc(obj, true)
              },500)
            }
          } else {
            nextTick(()=>{
              setTimeout(()=>{
                printFunc(obj, true)
              },500)
            })
          }
        }
      })
    }
  }


}

//打印并关闭
function clickPrintAndClose() {
  clickPrint()
  setTimeout(() => {
    handleClose()
  }, 1000)
}

//打印方法
function printFunc(printObj, isPrint) {
  html2canvas( proxy.$refs["printDiv" + printObj.receiptId][0], {
    backgroundColor: null,
  }).then((canvas) => {
    let url = canvas.toDataURL("image/png");
    if (LODOP) {
      LODOP.PRINT_INIT("");
      LODOP.ADD_PRINT_IMAGE(0, 0, "100%", "100%", url);
      LODOP.SET_PRINT_PAGESIZE(1, 2100, 2970)//设置纸张大小
      LODOP.SET_PRINTER_INDEX(printMachine.value) //设置打印机
      LODOP.PREVIEW()
    }
  })

  // if(isPrint){
  //   LODOP.PRINT()
  // }else{
  //   LODOP.PREVIEW()
  // }

}

function changePrintNum() {
  printNumTotal.value = 0
  tableData.value.map(item => {
    printNumTotal.value += item.printNum * 1
  })
}

//获取默认打印机
function getGoodsTempList() {
  let params = {
    pageSize: 0,
    param: {printType: 6, statusSort: true}
  }
  getPrintConfigList(params).then(res => {
    if (res.code === 200) {
      //设置 默认打印机
      printMachine.value = res.data[0].printMachine

    }
  })

}
</script>

<style scoped lang="scss">

</style>